﻿using System;

/*
 * 14 Write a program that exchanges bits 3, 4 and 5 with bits 24, 25 and 26 of given 32-bit unsigned integer.
 * 13 Write a program that exchanges bits {p, p+1, …, p+k-1) with bits {q, q+1, …, q+k-1} of given 32-bit unsigned integer.
 */

class ExchangeBitSequenceWithinAnInteger
{
    static void Main(string[] args)
    {
        uint number = 40;
        //uint number = 4294901760;
        //uint number = 4294967295;
        int exchangePosition1 = 3;
        int exchangePosition2 = 24;
        int numberOfBitsToExchange = 3;

        String numberBinary = Convert.ToString(number, 2).PadLeft(32, '0');
        Console.WriteLine("In the binary representation of {0}:\n{1}\nexchange the {2} bits starting from position {3}\nwith the {2} bits starting from position {4}."
                            , number, numberBinary, numberOfBitsToExchange, exchangePosition1, exchangePosition2);

        uint mask1 = 0;
        uint mask2 = 0;
        for (int i1 = exchangePosition1, i2 = exchangePosition2; i1 < exchangePosition1 + numberOfBitsToExchange; i1++, i2++)
        {
            mask1 += (uint)Math.Pow(2, i1);
            mask2 += (uint)Math.Pow(2, i2);
        }
        uint numberAndMask1 = number & mask1;
        uint numberAndMask2 = number & mask2;
        uint numberAndMask1Exchanged = numberAndMask1 << (exchangePosition2 - exchangePosition1);
        uint numberAndMask2Exchanged = numberAndMask2 >> (exchangePosition2 - exchangePosition1);
        uint numberWithCleanExchangePosiotions = ((number & ~mask1)& ~mask2);
        uint result = ((numberWithCleanExchangePosiotions | numberAndMask1Exchanged) | numberAndMask2Exchanged);
        String resultBinary = Convert.ToString(result, 2).PadLeft(32, '0');
        Console.WriteLine("The result is the number {0} with binary representation:\n{1}",result,resultBinary);
    }
}
